package com.fannnnn.system.filter;

import com.fannnnn.system.pojo.LoginUser;
import com.fannnnn.system.utils.JwtUtil;
import com.fannnnn.system.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * \*  Created with IntelliJ IDEA.
 * \*  @author shensifan
 * \*  Date: 2022/1/26
 * \*  Time: 15:53
 * \*  Description:
 * \
 */

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {



    @Autowired
    RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        /**
         * 获取token
         * */
        String token = request.getHeader("token");

        //判断token是否存在
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        /**
         * 解析token，从redis当中拿到我们需要的user信息
         * */
        String userid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        LoginUser loginUser = (LoginUser) redisUtil.get("User:" + userid);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录!");
        }

        //将loginUser存入SecurityContextHolder当中
        /**
         * 将用户的权限信息放入  authenticationToken 当中
         * */
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser.getUser(), null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);


    }
}
